from starlette.endpoints import HTTPEndpoint
from database import Session
from dao import DaoBureauWeeklyRepSum
from starlette.responses import JSONResponse
import pendulum
import logging


class BureauWeeklyRepSum(HTTPEndpoint):

    def __init__(self, scope):
        self._logger = logging.getLogger('WEEK_REP')
        return super().__init__(scope)

    async def get(self, request):
        session = Session()
        try:
            bureauid = request.query_params["bureauid"]
            monthnum = request.query_params["monthnum"]
            weeknum = request.query_params["weeknum"]
            return DaoBureauWeeklyRepSum.get_weeklyrep_write_info(session, bureauid, monthnum, weeknum)
        finally:
            session.close()

    async def put(self, request):
        session = Session()
        try:
            dict_bwrs = await request.json()
            entry_openid = request.user.open_id
            entry_name = request.user.display_name
            entry_time = pendulum.now()
            DaoBureauWeeklyRepSum.update_weekly_info_write(session, dict_bwrs, entry_openid, entry_name, entry_time)
            session.commit()
        except Exception:
            session.rollback()
            return JSONResponse({"result": "0"})
        else:
            from sqlalchemy.exc import SQLAlchemyError
            try:
                # 这里需要根据审核情况推送审核提醒
                # 审核提交信息推送
                if dict_bwrs['flag'] == '1':
                    from model.ModCompanyOperator import CompanyOperator
                    from model.ModDepartmentVsBureau import DepartmentVsBureau
                    from wxenterprise.wx_enterprise_message import send_to_user
                    bureauid = dict_bwrs["bureauid"]
                    monthnum = dict_bwrs["monthnum"]
                    weeknum = dict_bwrs["weeknum"]
                    target_auditor = session.query(CompanyOperator)\
                        .filter(CompanyOperator.audit_permission == '1')\
                        .filter(CompanyOperator.company_employee == '1')\
                        .all()
                    source_department = session.query(DepartmentVsBureau)\
                        .filter(DepartmentVsBureau.bureauid == bureauid)\
                        .first()
                    msg = f'{source_department.department_name}的{monthnum[0:7]}月' + \
                        f'第{weeknum}周周报已提交审核，请注意及时处理。'
                    for person in target_auditor:
                        send_to_user(person.openid, msg)
            except SQLAlchemyError:
                self._logger.warn(f'审核状态提醒发送失败，未找到目标人员。')
            finally:
                session.rollback()
            return JSONResponse({"result": "1"})
        finally:
            session.close()

class BureauWeeklyRepSumList(HTTPEndpoint):
    async def get(self, request):
        session = Session()
        try:
            monthnum = request.query_params["monthnum"]
            return DaoBureauWeeklyRepSum.get_weeklyrep_list(session, monthnum)
        finally:
            session.close()